//
//  CLLNetWorkManager.swift
//  CLWeiNo
//
//  Created by DDC on 2017/10/11.
//  Copyright © 2017年 DDC. All rights reserved.
//

import UIKit
import AFNetworking

enum CLLHttpMethod {
    case GET
    case POST
}

/// AFN网络封装
class CLLNetWorkManager: AFHTTPSessionManager {

    // 用户信息
    lazy var userAccount = CLLUserAccount()
    // 单例
    static let shared = CLLNetWorkManager()
//    // uid = "5365823342"
//    var uid:String? = "5365823342"
//    // token
//    var accessToken:String?// = "2.00Zzp2lB9kzLnCcdf33475dd_fSArC"
    // 用户登录标记
    var userLogon:Bool {
        return userAccount.access_token != nil
    }
    // 用于封装token的网络方法
    func tokenRequest(method:CLLHttpMethod = .GET,urlString:String,params:[String:Any]?,completion:@escaping (_ json:Any?,_ isSuccess:Bool)->()){
        // 判断是否有token,为nil直接返回
        guard let token = userAccount.access_token else {
            print("没有token,需要登录")
            // 添加需要登录的通知
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: CLLWBUserShouldLogonNotification), object: nil)
            // 回调为空
            completion(nil, false)
            return
        }
        // 判断参数字典是否存在,如果为nil则新建一个字典
        var params = params
        
        if params == nil {
            
            params = [String : Any]()
        }
        // 此处token一定有值
        params!["access_token"] = token
        request(urlString: urlString, params: params, completion: completion)
        
        
    }
    
    // 用一个方封装GET/POST方法(默认get方法)
    func request(method:CLLHttpMethod = .GET,urlString:String,params:[String:Any]?,completion:@escaping (_ json:Any?,_ isSuccess:Bool)->()) {
        
        // 成功的回到
        let success = {(task:URLSessionDataTask,json:Any?)->() in
            
            completion(json, true)
        }
        // 失败的回调
        let failure = { (task:URLSessionDataTask?,error:Error)->() in
            completion(nil, false)
        }
        // 方法的封装
        if method == .GET {
            
            get(urlString, parameters: params, progress: nil, success:success, failure: failure)
            
        } else {
            
            post(urlString, parameters: params, progress: nil, success: success, failure: failure)
        }
        
        
    }

}
